package com.image.demo.browser;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONObject;

/**
 * 浏览器页面首页action
 * @author w.g
 * @date 2019-05-05
 * 
 */
@Controller
@RequestMapping("browserIndex/browserIndex.do")
public class BrowserIndexController {
	/**
	 * TODO 
	 * @param req
	 * @return
	 */
	@RequestMapping(params="method=index")
	public ModelAndView index(HttpServletRequest req,String imgType) {
		ModelAndView model = new ModelAndView();
		JSONObject obj = getAllImgs(req);
		model.addObject("data",obj);
		model.addObject("imgType",imgType);
		model.setViewName("browser/index");
		return model;
	}
	
	@RequestMapping(params="method=about")
	public String about() {
		return "browser/about";
	}
	
	/**
	 * 获取所有图片
	 * @return
	 */
	private JSONObject getAllImgs(HttpServletRequest request) {
		JSONObject obj = new JSONObject();
		
		String[] types =new String[] {"fdmc","ty","tyfspt","tymhgd","tywl","tyxm"};//所有图片类型
		
		for (String type : types) {
			String path = request.getServletContext().getRealPath("/")+"static/images/"+type;
			File folder = new File(path);
			File[] listFiles = folder.listFiles();
			List<String> list = new ArrayList<String>();
			for (File file : listFiles) {
				if(checkImg(file.getName())) {
					list.add(file.getName());
				}
			}
			obj.put(type, list);
		}
		return obj;
	}
	
	/**
	 * 判断文件是不是图片
	 * @param fileName
	 * @return
	 */
	public boolean checkImg(String fileName) {
		if(fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".bmp") || 
				fileName.endsWith(".jpeg") || fileName.endsWith(".tif")) {
			return true;
		}
		return false;
	}
}
